<?php

namespace tool;

/**
 * Description of Map
 *
 * @author zy
 */
class Map {

    private $width;
    private $height;

    public function __construct($width, $height)
    {
        $this->width = $width;
        $this->height = $height;
    }

    public function getRandom()
    {
        return [
            mt_rand(0, $this->width),
            mt_rand(0, $this->height)
        ];
    }

    /**
     * 坐标转换字符串
     * @param int $x
     * @param int $y
     * @return string
     */
    static public function xyToString(int $x, int $y): string
    {
        return $x . ',' . $y;
    }

    /**
     * 坐标字符串 转 坐标
     * @param string $string
     * @return type
     */
    static public function stringToXy(string $string)
    {
        return explode(',', $string);
    }

    /**
     * 解码 
     * tile数字转x,y坐标
     * @param type $tileIndex
     */
    public function decode(int $tile_num): array
    {
        $tile_num -= 1;
        $x = $this->getX($tile_num + 1, $this->width);
        $y = (int) floor($tile_num / $this->width);
        return array( $x,  $y);
    }

    /**
     * 获取 坐标X 的位置
     * @param type $num
     * @param type $w
     * @return int
     */
    protected function getX($num, $w)
    {
        if ($num == 0) {
            return 0;
        }
        return ($num % $w == 0) ? $w - 1 : ($num % $w) - 1;
    }

    /**
     * 根据 位置X,Y 获取 切片索引
     * @param type $x
     * @param type $y
     * @return type
     */
    public function GridPositionToTileIndex($x, $y)
    {
        return ($y * $this->width) + $x + 1;
    }

}
